package com.hoopchina.weibo.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.hoopchina.news.R;
import com.hoopchina.meta.BindItem;
import com.hoopchina.settings.SettingsActivity;
import com.hoopchina.ui.main.BaseActivity;
import com.hoopchina.ui.main.TitleBar;
import com.hoopchina.ui.main.ViewManager;
import com.hoopchina.util.UrlUtils;
import com.hoopchina.util.download.DownloadCallback;
import com.hoopchina.util.download.DownloadTask;
import com.hoopchina.util.download.Downloader;

/**
 * 
 * @author neusoft
 * 
 */
public class BindingPageActivity extends BaseActivity {
	public static final String TAG = "BindingPageActivity";
	public static final String Id = "BindingPageActivity";
	private static final int MSG_REFRESH_LIST = 1;
	private static final String HEAD_IMAGE_SAVE_PATH = "/BindImages/";
	private ViewManager mViewManager = null;
	private BindingListAdaptor listItemAdapter = null;
	private ArrayList<BindItem> listData = null;
	private ListView mListView = null;
	private BindingDBEngine mEngine = null;
	private List<BindItem> mBindList = null;
	private TitleBar mTitleBar = null;
	private ArrayAdapter<String> mBindAdapter = null;
	private Spinner mBindSpinner = null;	// 添加绑定Spinner
	private List<String> mBindSpinnerList = new ArrayList<String>();
	private int mWeiboType = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
	}
	
	/**
	 * 初始化
	 */
	private void init() {
		mMyHandleBackButton = true;
		setContentView(R.layout.mybindingview);
		mViewManager = ViewManager.getInstance();
		mTitleBar = (TitleBar) findViewById(R.id.bindingViewTitleBar);
		mBindSpinnerList.add(getResources().getString(R.string.weibo_sina));
		mBindSpinnerList.add(getResources().getString(R.string.weibo_tencent));
		mBindSpinnerList.add(getResources().getString(R.string.weibo_sohu));
		mBindSpinnerList.add(getResources().getString(R.string.weibo_netease));
		mBindSpinnerList.add(getResources().getString(R.string.weibo_renren));
		mViewManager.setTitle(getString(R.string.app_menu_my_binding));
		mViewManager.hideLeftButton();
		mViewManager.setTabBarVisibility(false);
	}

	/**
	 * 消息处理
	 */
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_REFRESH_LIST:
				listItemAdapter.notifyDataSetChanged();
				break;
			}
		}
	};

	@Override
	public void onResume() {
		super.onResume();
		mTitleBar.setVisibility( View.VISIBLE );
		mTitleBar.setTitle( getResources().getString( R.string.mybinding_title ) );
		mTitleBar.displayWeatherBox( false );
		mTitleBar.setStatus( "" );
		mTitleBar.setAssistButton( "", R.drawable.titlebar_btn_assist_selector,
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						finish();
						SettingsActivity.destroyActivity();
					}
				});

		mEngine = new BindingDBEngine(BindingPageActivity.this);
		mBindList = mEngine.getBindingList();
		if (mBindList != null && mBindList.size() != 0) {
			listData = new ArrayList<BindItem>();
			listItemAdapter = new BindingListAdaptor(this, listData);
			mListView = (ListView) findViewById(R.id.bindingviewList);
			mListView.setAdapter(listItemAdapter);
			initBindingList();
			initHeadImages();
		} else {
			Toast.makeText(this,
					getResources().getString(R.string.forward_no_binding),
					Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void goBack() {
		finish();
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.addbindingview, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_addbingview_add:
			openAddBindingDialog();
			break;
		case R.id.menu_addbingview_home:
			finish();
			SettingsActivity.destroyActivity();
			break;
		case R.id.menu_addbingview_setting:
			finish();
			break;
		default:
			break;
		}
		return false;
	}
	
	/**
	 * 初始化绑定列表
	 */
	private void initBindingList() {
		for (int i = 0; i < mBindList.size(); i++) {
			String imageUrl = mBindList.get(i).getHeadUrl();
			BindItem bindItem = new BindItem();
			bindItem.setType(mBindList.get(i).getType());
			bindItem.setScreenName(mBindList.get(i).getScreenName());
			bindItem.setSite(mBindList.get(i).getSite());
			bindItem.setHeadUrl(imageUrl);
			listData.add(bindItem);
		}
		listItemAdapter.notifyDataSetChanged();
	}
	
	/**
	 * 初始化头像
	 */
	private void initHeadImages() {
		for (int i = 0; i < mBindList.size(); i++) {
			String imageUrl = mBindList.get(i).getHeadUrl();
			String imagePath = getCacheDir() + HEAD_IMAGE_SAVE_PATH
					+ UrlUtils.getNameFromUrl(imageUrl);
			final File file = new File(imagePath);
			if (!file.exists()) {
				File savePath = new File(getCacheDir() + HEAD_IMAGE_SAVE_PATH);
				if (!savePath.exists()) {
					savePath.mkdirs();
				}
				Downloader.getInstance().download(imageUrl,
						getCacheDir() + HEAD_IMAGE_SAVE_PATH,
						new DownloadCallback() {
							@Override
							public void onFinished(DownloadTask finishedTask) {
								if (file.exists()) {
									mHandler.sendEmptyMessage(MSG_REFRESH_LIST);
								}
							}

							@Override
							public void onFailed() {
							}
						});
			}
		}
		listItemAdapter.notifyDataSetChanged();
	}
	
	/**
	 * 打开添加绑定对话框
	 */
	public void openAddBindingDialog() {
		LayoutInflater mInflater = LayoutInflater
				.from(BindingPageActivity.this);
		View addBindingview = mInflater
				.inflate(R.layout.addbindingdialog, null);
		mBindSpinner = (Spinner) addBindingview
				.findViewById(R.id.addBindingSelectSpinner);
		mBindAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, mBindSpinnerList);
		mBindAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mBindSpinner.setAdapter(mBindAdapter);

		mBindSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				mWeiboType = position;
			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		AlertDialog.Builder bindDialog = new AlertDialog.Builder(
				BindingPageActivity.this);
		bindDialog.setTitle(getResources().getString(
				R.string.add_binding_dialog_title));
		bindDialog.setView(addBindingview);
		bindDialog.setPositiveButton(
				getResources().getString(
						R.string.add_binding_dialog_button_confirm),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Bundle aBundle = new Bundle();
						aBundle.putInt("WeiboType", mWeiboType);
						aBundle.putBoolean("FromBindingPage", true);
						aBundle.putString("Title", "");

						BindingDBEngine mEngine = new BindingDBEngine(
								BindingPageActivity.this);
						mEngine.removeBindingItem(mWeiboType);
						WeiboAuthActivity.setOldView(BindingPageActivity.Id,
								BindingPageActivity.class);
						Intent intent = new Intent();
						intent.putExtras(aBundle);
						intent.setClass(BindingPageActivity.this,
								WeiboAuthActivity.class);
						startActivity(intent);
						dialog.dismiss();
					}
				});
		bindDialog.setNegativeButton(
				getResources().getString(
						R.string.add_binding_dialog_button_cancel),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		bindDialog.create().show();
	}
}
